package pe.com.bbva.mantenimiento.action;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import pe.com.bbva.mantenimiento.bo.BinBO;
import pe.com.bbva.mantenimiento.bo.TipoTarjetaBO;
import pe.com.bbva.mantenimiento.domain.Bin;
import pe.com.bbva.mantenimiento.domain.Tabla;
import pe.com.bbva.mantenimiento.domain.TipoTarjeta;
import pe.com.bbva.util.Constantes;
import pe.com.bbva.util.SelectItem;
import pe.com.stefanini.core.action.GenericAction;
import pe.com.stefanini.core.domain.UsuarioSession;
import pe.com.stefanini.core.exceptions.BOException;
import pe.com.stefanini.core.exceptions.DAOException;
import pe.com.stefanini.core.service.ServiceUtil;
import pe.com.stefanini.core.util.StringUtil;

@Service("binAction")
@Scope("prototype")
@Results({
	@Result(name="viewListBin",type="tiles", location="viewListBin"),
	@Result(name="viewFormBin",type="tiles", location="viewFormBin"),
	@Result(name="listaBins",type="json",params={"root","grid"})
})
public class BinAction extends GenericAction {
	private static final long serialVersionUID = 1L;

	private Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private BinBO binBO;

	@Resource
	private TipoTarjetaBO tipoTarjetaBO;
	
	private Long idBin;
	private String codigoAntiguo;
	private Bin bin;
	private Bin binBuscar;
	private List<Bin> listaBins;
	private List<SelectItem> listaValPriority;

	public void cleanForm() {
		setIdBin(null);
		setCodigoAntiguo("");
		setBin(null);
		setBinBuscar(null);
	}
	
	@Action(value="initBin")
	public String init() {
		bin = new Bin();
		return "viewListBin";
	}
	
	@Action(value="findAllBin")
	public String findAll() {
		try {
			if (binBuscar == null) {
				binBuscar = new Bin();
			}
			setGrid(binBO.findToGrid(binBuscar,getSidx()+" "+getSord(),getPage(),getRows()));
			if(getGrid().getRecords().equals(new Integer(0))){
				addActionError("No se encontraron resultados");
			}
		} catch (BOException e) {
			logger.error(StringUtil.getStackTrace(e));
		} catch (Exception e) {
			logger.error(StringUtil.getStackTrace(e));
		}
		return "listaBins";
	}

	@Action(value="newBin")
	public String newForm() {
		return "viewFormBin";
	}
	
	@Action(value="updateBin")
	public String updateForm() {
		try {
			bin = binBO.findById(idBin);
			codigoAntiguo = bin.getCodigo();
		} catch (BOException e) {
			logger.error(StringUtil.getStackTrace(e));
		} catch (Exception e) {
			logger.error(StringUtil.getStackTrace(e));
		}
		return "viewFormBin";
	}

	@Action(value="deleteBin")
	public String delete() {
		try {
			String msjValidacion = validar(idBin);
			if(msjValidacion==null){
				binBO.deleteLog(Bin.class, idBin);
				addActionMessage("Eliminado Correctamente.");
			}else{
				addActionError(msjValidacion);
			}
		} catch (BOException e) {
			addActionError(e.getMessage());
			logger.error(StringUtil.getStackTrace(e));
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(StringUtil.getStackTrace(e));
		}
		return "viewListBin";
	}

	@Action(value="saveBin")
	public String save() {
		String forward = "";
		String mensaje = "";
		if (idBin == null) {
			mensaje = "Registrado Correctamente";
		} else {
			mensaje = "Actualizado Correctamente";
		}
		try {
			UsuarioSession usuarioSession = (UsuarioSession) getObjectSession(Constantes.USUARIO_SESSION);
			setCamposAuditoria(bin, usuarioSession);
			String msjValidacion = null;
			if(bin.getEstado().equals(Constantes.ESTADO_INACTIVO) && idBin != null){
				msjValidacion = validar(idBin);
			}
			if(msjValidacion==null){
				binBO.save(bin, codigoAntiguo);
				listaBins = binBO.findBins(new Bin());
				addActionMessage(mensaje);
				cleanForm();
				forward = "viewListBin";
			}else{
				addActionError(msjValidacion);
				forward = "viewFormBin";
			}
		} catch (BOException e) {
			forward = "viewFormBin";
			addActionError(e.getMessage());
			logger.error(StringUtil.getStackTrace(e));
		} catch (Exception e) {
			logger.error(StringUtil.getStackTrace(e));
		}
		return forward;
	}

	private String validar(Long idBin) throws BOException, DAOException {
		String msj = null;
		Bin bin = null;
		List<TipoTarjeta> listaTipoTarjeta = null;
		bin = binBO.findById(idBin);
		if(bin != null){
			TipoTarjeta tipoTarjeta = new TipoTarjeta();
			tipoTarjeta.setBin(bin);
			tipoTarjeta.setEstado(Constantes.VAL_ACTIVO);
			listaTipoTarjeta = tipoTarjetaBO.findTipos(tipoTarjeta);
		}
		if(listaTipoTarjeta!= null && !listaTipoTarjeta.isEmpty()){
			msj = "No se puede eliminar Bin. Tiene Tipos de Tarjeta relacionados.";
		}
		return msj;
	}
	
	public BinBO getBinBO() {
		return binBO;
	}

	public void setBinBO(BinBO binBO) {
		this.binBO = binBO;
	}

	public Long getIdBin() {
		return idBin;
	}

	public void setIdBin(Long idBin) {
		this.idBin = idBin;
	}

	public String getCodigoAntiguo() {
		return codigoAntiguo;
	}

	public void setCodigoAntiguo(String codigoAntiguo) {
		this.codigoAntiguo = codigoAntiguo;
	}

	public Bin getBin() {
		return bin;
	}

	public void setBin(Bin bin) {
		this.bin = bin;
	}

	public Bin getBinBuscar() {
		return binBuscar;
	}

	public void setBinBuscar(Bin binBuscar) {
		this.binBuscar = binBuscar;
	}

	public List<Bin> getListaBins() {
		return listaBins;
	}

	public void setListaBins(List<Bin> listaBins) {
		this.listaBins = listaBins;
	}

	public List<SelectItem> getListaValPriority() {
		return listaValPriority;
	}

	public void setListaValPriority(List<SelectItem> listaValPriority) {
		this.listaValPriority = listaValPriority;
	}


}
